package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.ICON_TRANSFER_NOTIFY
import com.example.library_common.utils.even.MessageWrap
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.CollectedCoinsFragmentBinding
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.CurrencyTransferIntentBean
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.MyOrderResultBean
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.PushMsgManager
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.SaveTxBuyOrderPayBean
import com.example.shushiyunsst.util.COMPLAINT
import com.example.shushiyunsst.util.TO_ID
import com.example.shushiyunsst.util.clipboard
import com.example.shushiyunsst.util.startNavigation
import com.example.wallet.db.UserInfoManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.ImageViewerPopupView
import com.lxj.xpopup.interfaces.XPopupImageLoader
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * 待收币
 * */
class CollectedCoinsFragment : BaseDataBindingFragment<CollectedCoinsFragmentBinding>(),
    View.OnClickListener {

    companion object {

        fun newInstance(toId: String): CollectedCoinsFragment {
            val args = Bundle()
            args.putString("toId", toId)
            val fragment = CollectedCoinsFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var toId: String? = null

    private var mToolbar: Toolbar? = null

    private var mResultBean: MyOrderResultBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        toId = arguments?.getString("toId")
    }

    override fun layoutId(): Int {
        return R.layout.collected_coins_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mToolbar = view.findViewById(R.id.mToolbar)
//        mToolbar?.title = mBean?.order?.orderDesc
        mToolbar?.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.onViewClick = this
//        viewBinder.mBean = mBean
        viewBinder.mProgressBar.visibility=View.VISIBLE

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "toid" to toId,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryTxOrderById)
            .success {
//                viewBinder.mProgressBar.visibility = View.GONE
                parseQueryTxOrder(it)
                viewBinder.mProgressBar.visibility=View.GONE

            }.failure {
                Toast.makeText(_mActivity, "获取订单详情失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.build().post()

    }

    private fun parseQueryTxOrder(it: String?) {
        mResultBean = JSON.parseObject(it, MyOrderResultBean::class.java)
        viewBinder.mBean = mResultBean
        mToolbar?.title = mResultBean?.order?.orderDesc
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.toComplaint -> {
                ARouter.getInstance()
                    .build(COMPLAINT)
                    .withString(TO_ID, mResultBean?.order?.toid.toString())
                    .startNavigation(this)
            }
            R.id.waiting -> {
                val findFragment = findFragment(MyOrderCurrencyFragment::class.java)
                if (findFragment !=null){
                    popTo(MyOrderCurrencyFragment::class.java,false)
                }else{
                    startWithPop(MyOrderCurrencyFragment.newInstance())
                }
//                startWithPop(MyOrderCurrencyFragment.newInstance())
            }

            R.id.bankCardPayBankNo -> {
                clipboard("bankCardPayBankNo", mResultBean?.payment?.bankNo ?: "")
            }

            R.id.bankCardPayRealName -> {
                clipboard("bankCardPayRealName", mResultBean?.payment?.realName ?: "")
            }

            R.id.bankCardPayBankNameChild -> {
                clipboard("bankCardPayBankNameChild", mResultBean?.payment?.bankNameChild ?: "")
            }

            R.id.bankCardPayBankName -> {
                clipboard("bankCardPayBankNameChild", mResultBean?.payment?.bankName ?: "")
            }

            R.id.weiChatPayAccount -> {
                clipboard("weiChatPayAccount", mResultBean?.payment?.wxAccount ?: "")
            }

            R.id.weiChatPayRealName -> {
                clipboard("weiChatPayRealName", mResultBean?.payment?.realName ?: "")
            }

            R.id.aliPayAccount -> {
                clipboard("aliPayAccount", mResultBean?.payment?.alipayAccount ?: "")
            }

            R.id.aliPayRealName -> {
                clipboard("aliPayAccount", mResultBean?.payment?.realName ?: "")
            }

            R.id.aliPayPic -> {
                val imageViewerPopupView = ImageViewerPopupView(_mActivity)
                imageViewerPopupView.setImageUrls(listOf(mResultBean?.payment?.alipayUrl))
                imageViewerPopupView.setXPopupImageLoader(object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        GlideApp.with(this@CollectedCoinsFragment)
                            .load(uri)
                            .centerInside()
                            .into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return File(uri.toString())
                    }
                })
                XPopup.Builder(_mActivity)
                    .asCustom(imageViewerPopupView)
                    .show()
            }

            R.id.weiChatPayPic -> {
                val imageViewerPopupView = ImageViewerPopupView(_mActivity)
                imageViewerPopupView.setImageUrls(listOf(mResultBean?.payment?.wxUrl))
                imageViewerPopupView.setXPopupImageLoader(object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        GlideApp.with(this@CollectedCoinsFragment)
                            .load(uri)
                            .centerInside()
                            .into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return File(uri.toString())
                    }
                })
                XPopup.Builder(_mActivity)
                    .asCustom(imageViewerPopupView)
                    .show()
            }
        }
    }

    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        when (msg?.message) {
            ICON_TRANSFER_NOTIFY -> {
                val iconPushMsgList = PushMsgManager.getInstance().iconPushMsgList
                var flags = false
                for (e in iconPushMsgList) {
                    if (e.orderId == mResultBean?.order?.txNo) {
                        flags = true
                        break
                    }
                }

                if (flags) {
                    viewBinder.waiting.text = "对方已放币"
                    viewBinder.waiting.helper.backgroundColorNormal =
                        ContextCompat.getColor(_mActivity, R.color.PrimaryColor)
                    mToolbar?.title = "已放币"
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        val iconPushMsgList = PushMsgManager.getInstance().iconPushMsgList
        var index = -10
        for (i in 0 until iconPushMsgList.size) {
            val pushMsgBean = iconPushMsgList[i]
            if (pushMsgBean.orderId == mResultBean?.order?.txNo) {
                index = i
                break
            }
        }

        if (index >= 0) {
            val pushMsgBean = iconPushMsgList[index]
            iconPushMsgList.removeAt(index)
            iconPushMsgList.remove(pushMsgBean)
        }
        EventBus.getDefault().post(MessageWrap.getInstance(ICON_TRANSFER_NOTIFY))
    }


}